//
//  KuangViewController.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/10/23.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftyJSON
import SwiftyUserDefaults


class KuangViewController: BaseViewController ,UITableViewDelegate, UITableViewDataSource{
    var tempArr = NSMutableArray()
    var tempArr1 = NSMutableArray()
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    var num = Int()
    
    var rightBtn : UIButton! = nil
    var leftBtn : UIButton! = nil
    var mnType : NSString! = ""
    var realyType : NSString! = ""
    let needModel = BaseModel()
    var allnumber = Int()
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    private lazy var myTableView:UITableView = {
        var tempheight = CGFloat()
        if UIDevice.current.isX(){
            tempheight = 104 + 24
        }else{
            tempheight = 104
        }
        
        let myTableView = UITableView(frame: CGRect(x: 0, y: tempheight, width: kScreenWidth, height: self.view.frame.height - 104), style: UITableViewStyle.grouped)
        
        myTableView.delegate = self
        myTableView.separatorStyle = .none
        myTableView.backgroundColor = UIColor.clear
        //myTableView.backgroundColor = UIColor("#060D32")
        myTableView.dataSource = self
        myTableView.register(UINib.init(nibName: "KuangJiTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        
        header.setRefreshingTarget(self, refreshingAction: #selector(RecordingListViewController.headerRefresh))
        // 现在的版本要用mj_header
        // 上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: #selector(RecordingListViewController.footerRefresh))
        myTableView.mj_footer = footer
        myTableView.mj_footer.isHidden = false
        myTableView.mj_header = header
        return myTableView
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        num = 1
        mnType = "1"
        self.realyType = "1"
        getData()
        self.makeBaseUI()
        
        OYCountDownManager.sharedManager.start()
        
        self.view.backgroundColor = UIColor("#060D32")
        self.title = XALanguageManager.getString(key: "Mining progress")
        if UIDevice.current.isX(){
            rightBtn = UIButton.init(frame: CGRect(x: kScreenWidth/2, y: 88, width: kScreenWidth/2, height: 40))
        }else{
            rightBtn = UIButton.init(frame: CGRect(x: kScreenWidth/2, y: 64, width: kScreenWidth/2, height: 40))
        }
        
        
        
        rightBtn.setTitleColor(UIColor("#C1C3C9"), for: .normal)
        rightBtn.setTitleColor(UIColor("#3787FF"), for: .selected)
        rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        rightBtn.setTitle(XALanguageManager.getString(key: "N 释放进度"), for: .normal)
        rightBtn.addTarget(self, action: #selector(self.rightBtnAction), for: .touchUpInside)
        self.view.addSubview(rightBtn)
        
        if (UIDevice.current.isX()) {
            leftBtn = UIButton.init(frame: CGRect(x: 0, y: 88, width: kScreenWidth/2, height: 40))
        }else{
            leftBtn = UIButton.init(frame: CGRect(x: 0, y: 64, width: kScreenWidth/2, height: 40))
        }
        
        leftBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        leftBtn.setTitleColor(UIColor("#C1C3C9"), for: .normal)
        leftBtn.setTitleColor(UIColor("#3787FF"), for: .selected)
        leftBtn.addTarget(self, action: #selector(self.leftBtnAction), for: .touchUpInside)
        leftBtn.setTitle(XALanguageManager.getString(key: "M 释放进度"), for: .normal)
        leftBtn.isSelected = true
        self.view.addSubview(leftBtn)
        
        // Do any additional setup after loading the view.
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新")
        num = 1
        
        getData()
    }
    
    // 底部刷新
    @objc func footerRefresh(){
        num = 1 + num
        getData()
        print("上拉刷新")
    }
    
    @objc func leftBtnAction(){
        // left M
        self.myTableView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        self.leftBtn.isSelected = true
        self.rightBtn.isSelected = false
        mnType = "1"
        num = 1
        self.getData()
        
    }
    @objc func rightBtnAction(){
        // right N
    self.myTableView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        self.rightBtn.isSelected = true
        self.leftBtn.isSelected = false
        mnType = "2"
        num = 1
        self.getData()
    }
    
    func getData() {
        MyNetwork.request(target: .miningProgress(user_id: Defaults[.userID]!, limit: "10", page: String(format:"%d",num), type: mnType as String), success: { (result) in
            kLog(result)
            
            
            self.needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            if self.num == 1{
                self.tempArr = []
                self.tempArr = NSMutableArray()
            }
            self.footer.endRefreshing()
            self.header.endRefreshing()
            if self.needModel.code == 1111{
                if self.mnType == "2"{
                    let tempArr1 = NSMutableArray.yy_modelArray(with: productModel.self, json: (self.needModel.mydata!["n_list"] as! Dictionary)["data"]!)
                    
                    for tempModel in tempArr1!{
                        self.tempArr.add(tempModel as! productModel)
                    }
                    if (tempArr1?.count)! < 10{
                        self.footer.endRefreshingWithNoMoreData()
                    }
                    
                    self.allnumber =  (self.needModel.mydata!["n_list"] as! Dictionary<String, Any>)["total"] as! Int
                }else{
                    let tempArr1 = NSMutableArray.yy_modelArray(with: productModel.self, json: (self.needModel.mydata!["m_list"] as! Dictionary)["data"]!)
                    
                    for tempModel in tempArr1!{
                        self.tempArr.add(tempModel as! productModel)
                    }
                    if (tempArr1?.count)! < 10{
                        self.footer.endRefreshingWithNoMoreData()
                    }
                    self.allnumber =  (self.needModel.mydata!["m_list"] as! Dictionary<String, Any>)["total"] as! Int
                }
                self.realyType = self.mnType
                self.myTableView.reloadData()
                
            }else{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "失败"))
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
            self.footer.endRefreshing()
            self.header.endRefreshing();
            self.navigationController?.view.makeToast(error.localizedDescription)
        }
    }
    
    func makeBaseUI(){
        self.view.addSubview(myTableView)
    }
    //MARK: - tableView Delegate And DataSource
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell:KuangJiTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "cell")as?KuangJiTableViewCell
        if cell == nil {
            cell = KuangJiTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
        }
        
        cell.mnType = self.realyType  as String
        cell.number = (((self.tempArr as NSMutableArray)[indexPath.section] as! productModel).list as! Array<NSDictionary>)[indexPath.row]["user_index"] as? Int
        cell.isfirst = indexPath.row
        cell.typeNumber = 0
        cell.myDic = (((self.tempArr as NSMutableArray)[indexPath.section] as! productModel).list as! Array<NSDictionary>)[indexPath.row]
        
        //        cell.model = self.tempArr[indexPath.row] as! productModel
        
        //        cell.numberM = String(format: "%d", indexPath.section + 1) as NSString
        
        return cell!
    }
    //footer height
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 30
    }
    // row height
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    
    // header height
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let backView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 30))
        backView.backgroundColor = UIColor.clear
        
        let titleLabel = UILabel(frame: CGRect(x: 15, y: 0, width: kScreenWidth - 30, height: 30))
        titleLabel.textColor = UIColor("#909090")
        titleLabel.font = UIFont.boldSystemFont(ofSize: 10)
        titleLabel.textAlignment = .center
        if self.realyType == "2"{
            titleLabel.text = String(format: "MT%@  %@       MT%@ %@       %@DKE %@",XALanguageManager.getString(key: "总值"),(((self.tempArr as NSMutableArray)[section] as! productModel).total_n)!,XALanguageManager.getString(key: "剩余"),(((self.tempArr as NSMutableArray)[section] as! productModel).wei_n)!,XALanguageManager.getString(key: "已产出"),(((self.tempArr as NSMutableArray)[section] as! productModel).d_dke)! );
        }else{
            titleLabel.text = String(format: "CD%@ %@       CD%@ %@       %@DKE %@",XALanguageManager.getString(key: "总值"),(((self.tempArr as NSMutableArray)[section] as! productModel).total_m)!,XALanguageManager.getString(key: "剩余"),(((self.tempArr as NSMutableArray)[section] as! productModel).wei_m)! ,XALanguageManager.getString(key: "已产出"),(((self.tempArr as NSMutableArray)[section] as! productModel).d_dke)! );
        }
        titleLabel.adjustsFontSizeToFitWidth = true
        backView.addSubview(titleLabel)
        
        return backView
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if (((self.tempArr as NSMutableArray)[section] as! productModel).type)! == "2" {
            let backView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 50))
            backView.backgroundColor = UIColor("#1F2647")
            
            let titleLabel = UILabel(frame: CGRect(x: 15, y: 10, width: 100, height: 30))
            
            titleLabel.textColor = UIColor("#3787FF")
            titleLabel.font = UIFont.boldSystemFont(ofSize: 23)
            backView.addSubview(titleLabel)
            
            let tempView01 = UIView(frame: CGRect(x: 100 + 125, y: 20, width: 15, height: 15))
            tempView01.backgroundColor = UIColor("#26DBCC")
            backView.addSubview(tempView01)
            
            let tempLabel01 = UILabel(frame: CGRect(x: tempView01.frame.maxX + 10, y: 20, width: 100, height: 15))
            if self.realyType == "2"{
                tempLabel01.text = String(format: "%@ %@",XALanguageManager.getString(key: "未保N值"),(((self.tempArr as NSMutableArray)[section] as! productModel).can_baozhi_n)!)
                titleLabel.text = String(format: "MT%d", self.allnumber - section)
            }else {
                tempLabel01.text = String(format: "%@ %@",XALanguageManager.getString(key: "未保M值"),(((self.tempArr as NSMutableArray)[section] as! productModel).can_baozhi_m)!)
                titleLabel.text = String(format: "CD%d", self.allnumber - section)
            }
            tempLabel01.adjustsFontSizeToFitWidth = true
            tempLabel01.textColor = UIColor("#26DBCC")
            backView.addSubview(tempLabel01)
            tempLabel01.font = UIFont.systemFont(ofSize: 12)
            
            let tempView02 = UIView(frame: CGRect(x: tempLabel01.frame.maxX, y: 20, width: 15, height: 15))
            tempView02.backgroundColor = UIColor("#AB46BB")
            tempView02.isHidden = true
            backView.addSubview(tempView02)
            
            let tempLabel02 = UILabel(frame: CGRect(x: tempView02.frame.maxX + 10, y: 20, width: 100, height: 15))
            tempLabel02.isHidden = true
            tempLabel02.text = "已全部保值"
            tempLabel02.textColor = UIColor("#AB46BB")
            backView.addSubview(tempLabel02)
            tempLabel02.font = UIFont.systemFont(ofSize: 12)
            tempLabel02.adjustsFontSizeToFitWidth = true
            if  self.realyType == "2" {
                tempLabel02.text = String(format: "%@ %@",XALanguageManager.getString(key: "已保N值"),(((self.tempArr as NSMutableArray)[section] as! productModel).baozhi_n)!)
            }else{
                tempLabel02.text = String(format: "%@ %@",XALanguageManager.getString(key:"已保M值"),(((self.tempArr as NSMutableArray)[section] as! productModel).baozhi_m)!)
            }
            tempLabel01.text = XALanguageManager.getString(key: "推广所得N")
            
            return backView
        }else{
            let backView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 50))
            backView.backgroundColor = UIColor("#1F2647")
            
            let titleLabel = UILabel(frame: CGRect(x: 15, y: 10, width: 100, height: 30))
            
            titleLabel.textColor = UIColor("#3787FF")
            titleLabel.font = UIFont.boldSystemFont(ofSize: 23)
            backView.addSubview(titleLabel)
            
            let tempView01 = UIView(frame: CGRect(x: 100, y: 20, width: 15, height: 15))
            tempView01.backgroundColor = UIColor("#458FF6")
            backView.addSubview(tempView01)
            
            let tempLabel01 = UILabel(frame: CGRect(x: tempView01.frame.maxX + 10, y: 20, width: 100, height: 15))
            if self.realyType == "2"{
                tempLabel01.text = String(format: "%@ %@",XALanguageManager.getString(key: "未保N值"),(((self.tempArr as NSMutableArray)[section] as! productModel).can_baozhi_n)!)
                titleLabel.text = String(format: "MT%d", self.allnumber - section)
            }else {
                tempLabel01.text = String(format: "%@ %@",XALanguageManager.getString(key: "未保M值"),(((self.tempArr as NSMutableArray)[section] as! productModel).can_baozhi_m)!)
                titleLabel.text = String(format: "CD%d", self.allnumber - section)
            }
            tempLabel01.adjustsFontSizeToFitWidth = true
            tempLabel01.textColor = UIColor("#3787FF")
            backView.addSubview(tempLabel01)
            tempLabel01.font = UIFont.systemFont(ofSize: 12)
            
            let tempView02 = UIView(frame: CGRect(x: tempLabel01.frame.maxX, y: 20, width: 15, height: 15))
            tempView02.backgroundColor = UIColor("#AB46BB")
            backView.addSubview(tempView02)
            
            let tempLabel02 = UILabel(frame: CGRect(x: tempView02.frame.maxX + 10, y: 20, width: 100, height: 15))
            tempLabel02.text = "已全部保值"
            tempLabel02.textColor = UIColor("#AB46BB")
            backView.addSubview(tempLabel02)
            tempLabel02.font = UIFont.systemFont(ofSize: 12)
            tempLabel02.adjustsFontSizeToFitWidth = true
            if  self.realyType == "2" {
                tempLabel02.text = String(format: "%@ %@",XALanguageManager.getString(key: "已保N值"),(((self.tempArr as NSMutableArray)[section] as! productModel).baozhi_n)!)
            }else{
                tempLabel02.text = String(format: "%@ %@",XALanguageManager.getString(key:"已保M值"),(((self.tempArr as NSMutableArray)[section] as! productModel).baozhi_m)!)
            }
            return backView
        }
        
        
        
        
        
        
        //            let tempView03 = UIView(frame: CGRect(x: tempLabel02.frame.maxX + 10, y: 20, width: 15, height: 15))
        //            tempView03.backgroundColor = UIColor("#F952D3")
        //            backView.addSubview(tempView03)
        //
        //            let tempLabel03 = UILabel(frame: CGRect(x: tempView03.frame.maxX + 10, y: 20, width: 100, height: 15))
        //            tempLabel03.text = "不保值"
        //            backView.addSubview(tempLabel03)
        //            tempLabel03.font = UIFont.systemFont(ofSize: 12)
        
        //        }else{
        //            let tempView01 = UIView(frame: CGRect(x: 15, y: 20, width: 15, height: 15))
        //            tempView01.backgroundColor = UIColor("#00A291")
        //            backView.addSubview(tempView01)
        //
        //            let tempLabel01 = UILabel(frame: CGRect(x: tempView01.frame.maxX + 10, y: 20, width: 100, height: 15))
        //            tempLabel01.text = "完全释放"
        //            backView.addSubview(tempLabel01)
        //            tempLabel01.font = UIFont.systemFont(ofSize: 12)
        //
        //            let tempView02 = UIView(frame: CGRect(x: tempLabel01.frame.maxX, y: 20, width: 15, height: 15))
        //            tempView02.backgroundColor = UIColor("#FC364A")
        //            backView.addSubview(tempView02)
        //
        //            let tempLabel02 = UILabel(frame: CGRect(x: tempView02.frame.maxX + 10, y: 20, width: 100, height: 15))
        //            tempLabel02.text = "部分释放"
        //            backView.addSubview(tempLabel02)
        //            tempLabel02.font = UIFont.systemFont(ofSize: 12)
        //        }
        
    }
    
    
    // row num
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (((self.tempArr as NSMutableArray)[section] as! productModel).list?.count)!
        
    }
    // 组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.tempArr.count
    }
    
    //点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let vc = detailListViewController()
        vc.isMN = mnType as String!
        
        vc.wkId = String(format: " %@",(((self.tempArr as NSMutableArray)[indexPath.section] as! productModel).ids)!)
        
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    override func willMove(toParentViewController parent: UIViewController?) {
        
    }
    
    // MARK: - 懒加载
    
    
    //    //MARK - Private Methods
    //    func makeBaseUI(){
    //        //
    //        self.view.backgroundColor = UIColor("#EEF0F7")
    //
    //
    //        let backView = UIView(frame: CGRect(x: 15, y: 79, width: kScreenWidth - 30, height: 85))
    //        backView.backgroundColor = UIColor.white
    //        backView.layer.cornerRadius = 5
    //        self.view.addSubview(backView)
    //
    //        let photoImageView = UIImageView.init(frame: CGRect(x: 10, y: 20, width: 44, height: 44))
    //        backView.addSubview(photoImageView)
    //        photoImageView.image = UIImage.init(named: "组 1@2x")
    //
    //        let titleLabel = UILabel.init(frame: CGRect(x: 70, y: 20, width: 44, height: 44))
    //        titleLabel.text = "M"
    //        titleLabel.font = UIFont.boldSystemFont(ofSize: 20)
    //        backView.addSubview(titleLabel)
    //
    //
    //        let numberButton = PPNumberButton.init(frame: CGRect(x:kScreenWidth/2 - 50 - 15 , y: 27.5, width: 110, height: 30))
    //        numberButton.borderColor(UIColor.gray)
    //        //开启抖动动画
    //        numberButton.shakeAnimation = true
    //        numberButton.maxValue = 135
    //        numberButton.minValue = 1
    //        //加减按钮的闭包回调
    //        numberButton.numberResult { (number) in
    //
    //            print(number)
    //        }
    //
    //        backView.addSubview(numberButton)
    //
    //
    //        let myButton1 = UIButton()
    //        backView.addSubview(myButton1)
    //        myButton1.snp.makeConstraints { (make) in
    //            make.centerY.equalTo(backView)
    //            make.right.equalTo(backView).offset(-10)
    //            make.size.equalTo(CGSize(width: 80, height: 30))
    //        }
    //        myButton1.layer.cornerRadius = 15
    //        myButton1.backgroundColor = UIColor("#217AFF")
    //        myButton1.alpha = 0.7
    //        myButton1.titleLabel?.font = UIFont.systemFont(ofSize: 12)
    //        myButton1.setTitle("Preservation", for: .normal)
    //
    //        //        myButton1.addTarget(self, action: #selector(SecondViewController.), for: .touchUpInside)
    //
    //    }
    //
    //    override func didReceiveMemoryWarning() {
    //        super.didReceiveMemoryWarning()
    //        // Dispose of any resources that can be recreated.
    //    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
